package com.gao.flying.mq.consumer;

import com.gao.flying.mq.core.JmsContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.*;


public class JmsConsumer implements Runnable {

    private MessageListener messageListener = null;

    private JmsContext jmsContext;

    private String destinationName;
    private String type;
    private static Logger logger = LoggerFactory.getLogger(JmsConsumer.class);


    public JmsConsumer(String destinationName, String type, JmsContext jmsContext, MessageListener messageListener) {
        this.type = type;
        this.destinationName = destinationName;
        this.messageListener = messageListener;
        this.jmsContext = jmsContext;
    }


    public void run() {
        try {
            Session session = jmsContext.getSession();
            Destination destination;
            if (type.equalsIgnoreCase("queue")) {
                destination = session.createTopic(destinationName);
            } else {
                destination = session.createQueue(destinationName);
            }

            MessageConsumer messageConsumer = session.createConsumer(destination);
            messageConsumer.setMessageListener(messageListener);
        } catch (JMSException e) {
            logger.error(e.getMessage());
        }
    }

}
